#include "StdAfx.h"
//-------------------------------------------------------------------------------------------------
//ArchiveProcGUI.cpp : Defines the class behaviors for the application.         
//-------------------------------------------------------------------------------------------------
//FreeBSD License
//Copyright 2011 Will Stott All rights reserved.
//
//Redistribution and use in source and binary forms, with or without modification, are
//permitted provided that the following conditions are met:
//
//   1. Redistributions of source code must retain the above copyright notice, this list of
//      conditions and the following disclaimer.
//
//   2. Redistributions in binary form must reproduce the above copyright notice, this list
//      of conditions and the following disclaimer in the documentation and/or other materials
//      provided with the distribution.
//
//THIS SOFTWARE IS PROVIDED BY Will Stott ``AS IS'' AND ANY EXPRESS OR IMPLIED
//WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
//FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL Will Stott OR
//CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
//CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
//SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
//ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
//NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
//ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//The views and conclusions contained in the software and documentation are those of the
//authors and should not be interpreted as representing official policies, either expressed
//or implied, of Will Stott.
//
//----Authors--------------------------------------------------------------------------------------
//created by: will.stott@ucl.ac.uk July 2011
//
//----Comments-------------------------------------------------------------------------------------
//
//-------------------------------------------------------------------------------------------------

#include "afxwinappex.h"
#include "afxdialogex.h"
#include "UraDb.h"
#include "ArchiveProcGUI.h"
#include "MainFrm.h"

#include "ChildFrm.h"
#include "ArchiveProcGUIDoc.h"
#include "ArchiveProcGUIView.h"


#include "FreeBSDLicence.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#endif


// CArchiveProcGUIApp

BEGIN_MESSAGE_MAP(CArchiveProcGUIApp, CWinAppEx)
	ON_COMMAND(ID_APP_ABOUT, &CArchiveProcGUIApp::OnAppAbout)
	// Standard file based document commands
	ON_COMMAND(ID_FILE_NEW, &CWinAppEx::OnFileNew)
	ON_COMMAND(ID_FILE_OPEN, &CWinAppEx::OnFileOpen)
	// Standard print setup command
	ON_COMMAND(ID_FILE_PRINT_SETUP, &CWinAppEx::OnFilePrintSetup)
END_MESSAGE_MAP()


// CArchiveProcGUIApp construction

CArchiveProcGUIApp::CArchiveProcGUIApp() :
		m_gdiplusToken(0)
{
	m_bHiColorIcons = TRUE;

// support Restart Manager - The restart manager has three behaviour levels:
//1. Restart the application after it has crashed : AFX_RESTART_MANAGER_SUPPORT_RESTART
//2. Restart the application after it has crashed and reopen files : AFX_RESTART_MANAGER_SUPPORT_RESTART_ASPECTS
//3. Restart the application after it has crashed and reopen files, and use autosave : AFX_RESTART_MANAGER_SUPPORT_ALL_ASPECTS

#ifdef DEBUG
	m_dwRestartManagerSupportFlags = AFX_RESTART_MANAGER_SUPPORT_RESTART_ASPECTS;
#else
	m_dwRestartManagerSupportFlags = AFX_RESTART_MANAGER_SUPPORT_ALL_ASPECTS;
#endif

#ifdef _MANAGED
	// If the application is built using Common Language Runtime support (/clr):
	//     1) This additional setting is needed for Restart Manager support to work properly.
	//     2) In your project, you must add a reference to System.Windows.Forms in order to build.
	System::Windows::Forms::Application::SetUnhandledExceptionMode(System::Windows::Forms::UnhandledExceptionMode::ThrowException);
#endif

	// TODO: replace application ID string below with unique ID string; recommended
	// format for string is CompanyName.ProductName.SubProduct.VersionInformation
	SetAppID(_T("ArchiveProcGUI.AppID.NoVersion"));

	// TODO: add construction code here,
	// Place all significant initialization in InitInstance
}

// The one and only CArchiveProcGUIApp object

CArchiveProcGUIApp theApp;


// CArchiveProcGUIApp initialization

BOOL CArchiveProcGUIApp::InitInstance()
{

//!!!!!!!!!!!!!!!
#ifdef _DEBUG
	MxUtils::OutputDebugMsg("CArchiveProcGUIApp::InitInstance()", "program starts");
#endif
//!!!!!!!!!!!!!!!

	// InitCommonControlsEx() is required on Windows XP if an application
	// manifest specifies use of ComCtl32.dll version 6 or later to enable
	// visual styles.  Otherwise, any window creation will fail.
	INITCOMMONCONTROLSEX InitCtrls;
	InitCtrls.dwSize = sizeof(InitCtrls);
	// Set this to include all the common control classes you want to use
	// in your application.
	InitCtrls.dwICC = ICC_WIN95_CLASSES;
	InitCommonControlsEx(&InitCtrls);

	CWinAppEx::InitInstance();


	// Initialize OLE libraries
	if (!AfxOleInit())
	{
		AfxMessageBox(IDP_OLE_INIT_FAILED);
		return FALSE;
	}

	AfxEnableControlContainer();

	EnableTaskbarInteraction();

	// AfxInitRichEdit2() is required to use RichEdit control	
	// AfxInitRichEdit2();

	// Standard initialization
	// If you are not using these features and wish to reduce the size
	// of your final executable, you should remove from the following
	// the specific initialization routines you do not need
	// Change the registry key under which our settings are stored
	// TODO: You should modify this string to be something appropriate
	// such as the name of your company or organization

	SetRegistryKey(_T("UCL-IfWH"));

	if ( IsAutoSaveEnabled() )
		SetAutoFileSavePeriod(GetProfileInt(_T("General"), _T("AutoSavePeriod"), 5));			

	LoadStdProfileSettings(4);  // Load standard INI file options (including MRU)

	Gdiplus::GdiplusStartup(&m_gdiplusToken, &m_gdiplusStartupInput, NULL);

	InitContextMenuManager();

	InitKeyboardManager();

	InitTooltipManager();
	CMFCToolTipInfo ttParams;
	ttParams.m_bVislManagerTheme = TRUE;
	theApp.GetTooltipManager()->SetTooltipParams(AFX_TOOLTIP_TYPE_ALL,
		RUNTIME_CLASS(CMFCToolTipCtrl), &ttParams);

	// Register the application's document templates.  Document templates
	//  serve as the connection between documents, frame windows and views
	CMultiDocTemplate* pDocTemplate;
	pDocTemplate = new CMultiDocTemplate(IDR_ImageDatasetTYPE,
		RUNTIME_CLASS(CArchiveProcGUIDoc),
		RUNTIME_CLASS(CChildFrame), // custom MDI child frame
		RUNTIME_CLASS(CArchiveProcGUIView)); //RUNTIME_CLASS(CViewTree2)); 
	if (!pDocTemplate)
		return FALSE;
	AddDocTemplate(pDocTemplate);

	// create main MDI Frame window
	CMainFrame* pMainFrame = new CMainFrame;
	if (!pMainFrame || !pMainFrame->LoadFrame(IDR_MAINFRAME))
	{
		delete pMainFrame;
		return FALSE;
	}
	m_pMainWnd = pMainFrame;
	// call DragAcceptFiles only if there's a suffix
	//  In an MDI app, this should occur immediately after setting m_pMainWnd
	// Enable drag/drop open
	m_pMainWnd->DragAcceptFiles();

	// Parse command line for standard shell commands, DDE, file open
	CCommandLineInfo cmdInfo;
	ParseCommandLine(cmdInfo);

	// Enable DDE Execute open
	EnableShellOpen();
	RegisterShellFileTypes(TRUE);


	// Dispatch commands specified on the command line.  Will return FALSE if
	// app was launched with /RegServer, /Register, /Unregserver or /Unregister.
	if (!ProcessShellCommand(cmdInfo))
		return FALSE;
	// The main window has been initialized, so show and update it
	pMainFrame->ShowWindow(m_nCmdShow);
	pMainFrame->UpdateWindow();

	return TRUE;
}

int CArchiveProcGUIApp::ExitInstance()
{
	int rc = 0;

//!!!!!!!!!!!!!!!
#ifdef _DEBUG
	MxUtils::OutputDebugMsg("CArchiveProcGUIApp::ExitInstance()", "program ends");
	Sleep(1000);
#endif
//!!!!!!!!!!!!!!!

	//TODO: handle additional resources you may have added
	AfxOleTerm(FALSE);

	Gdiplus::GdiplusShutdown(m_gdiplusToken);

	rc = CWinAppEx::ExitInstance();

	return rc;
}


bool CArchiveProcGUIApp::SetAutoFileSavePeriod(int minutes)
{
	bool rc = false;

	if ( IsAutoSaveEnabled() )
	{
		int nAutosaveInterval;
		if (minutes <= 0 )
			nAutosaveInterval = CArchiveProcGUIApp::AutoSavePeriodFactoryDefault;
		else
			nAutosaveInterval = (minutes * 1000) * 60;

		if ( GetDataRecoveryHandler() != '\0')
		{
			GetDataRecoveryHandler()->SetAutosaveInterval(nAutosaveInterval);
			WriteProfileInt(_T("General"), _T("AutoSavePeriod"), minutes);
			rc = true;
		}
	}
	return rc;
}


const char *CArchiveProcGUIApp::GetRunTimeTypeName(CObject *obj) 
{ 
	const char *rc = "(runtime type unknown)";
	
	if (obj == '\0')
		rc = "(null)";
	else
	{													//			const type_info& ti = typeid(*obj);
		if (obj->IsKindOf(RUNTIME_CLASS(CObject)))		//			rc = ti.name();
		{
			CRuntimeClass *pRunTimeClass = obj->GetRuntimeClass();
			if (pRunTimeClass != '\0')
				rc = pRunTimeClass->m_lpszClassName;
		}
	}
	return rc; 
}


void CArchiveProcGUIApp::RestoreFactorySettings()
{
	CString empty("");

	SetDbConnection(L"DbConnectLabel-OCUDSDB", empty);
	SetDbConnection(L"DbConnectLabel-HPDEV", empty);
	SetImageDatasetFile(empty);
	SetDataDir(empty);
	SetSQLStatementFile(empty);
	SetImageSource(1);
	SetAutoFileSavePeriod(5);
}

CString CArchiveProcGUIApp::GetDbConnection(TCHAR *Label)
{
	CString rc(L""); 

	CString strSection       = _T("Database");
	rc = GetProfileString(strSection, Label);
	
	return rc;
}



bool	CArchiveProcGUIApp::SetDbConnection(TCHAR *Label, CString &connectStr)
{
	CString strSection       = _T("Database");
	
	WriteProfileString(strSection, Label, connectStr);

	return true;
}

CString	CArchiveProcGUIApp::GetImportImagesDir()
{
	CString rc(L""); 

	rc = GetProfileString(_T("IDF"), _T("DefaultImportImagesDir"));
	
	return rc;
}

bool	CArchiveProcGUIApp::SetImportImagesDir(CString &folder)
{

	WriteProfileString(_T("IDF"), _T("DefaultImportImagesDir"), folder);

	return true;
}

CString	CArchiveProcGUIApp::GetImageDatasetFile()
{
	CString rc(L""); 

	rc = GetProfileString(_T("IDF"), _T("DefaultDatasetFile"));
	
	return rc;
}

bool	CArchiveProcGUIApp::SetImageDatasetFile(CString &IdfFile)
{

	WriteProfileString(_T("IDF"), _T("DefaultDatasetFile"), IdfFile);

	return true;
}

CString	CArchiveProcGUIApp::GetDataDir()
{
	CString rc(L""); 

	rc = GetProfileString(_T("IDF"), _T("DefaultDataDir"));
	
	return rc;
}

bool	CArchiveProcGUIApp::SetDataDir(CString &DataDir)
{
	WriteProfileString(_T("IDF"), _T("DefaultDataDir"), DataDir);

	return true;
}

CString	CArchiveProcGUIApp::GetSQLStatementFile()
{
	CString rc(L""); 

	rc = GetProfileString(_T("IDF"), _T("DefaultSQLStatementFile"));
	
	return rc;
}

bool	CArchiveProcGUIApp::SetSQLStatementFile(CString &SqlStatementFile)
{
	WriteProfileString(_T("IDF"), _T("DefaultSQLStatementFile"), SqlStatementFile);
	return true;
}

int		CArchiveProcGUIApp::GetImageSource()
{
	int rc = 0; 

	rc = GetProfileInt(_T("IDF"), _T("DefaultImageSource"), 1);
	
	return rc;
}

bool	CArchiveProcGUIApp::SetImageSource(int SourceType)
{
	WriteProfileInt(_T("IDF"), _T("DefaultImageSource"), SourceType);
	return true;
}

CString	CArchiveProcGUIApp::GetIDFName()
{
	CString rc(L""); 

	rc = GetProfileString(_T("IDF"), _T("DefaultIDFName"));
	
	return rc;
}

bool	CArchiveProcGUIApp::SetIDFName(CString &name)
{
	WriteProfileString(_T("IDF"), _T("DefaultIDFName"), name);
	return true;
}

CString	CArchiveProcGUIApp::GetIDFOwner()
{
	CString rc(L""); 

	rc = GetProfileString(_T("IDF"), _T("DefaultIDFOwner"));
	
	return rc;
}
bool	CArchiveProcGUIApp::SetIDFOwner(CString &email)
{
	WriteProfileString(_T("IDF"), _T("DefaultIDFOwner"), email);
	return true;
}

CString	CArchiveProcGUIApp::GetIDFDescription()
{
	CString rc(L""); 

	rc = GetProfileString(_T("IDF"), _T("DefaultIDFDesc"));
	
	return rc;
}
bool	CArchiveProcGUIApp::SetIDFDescription(CString &desc)
{
	WriteProfileString(_T("IDF"), _T("DefaultIDFDesc"), desc);
	return true;
}

CString	CArchiveProcGUIApp::GetIDFVersion()
{
	CString rc(L""); 

	rc = GetProfileString(_T("IDF"), _T("DefaultIDFVersion"));
	
	return rc;
}
bool	CArchiveProcGUIApp::SetIDFVersion(CString &version)
{
	WriteProfileString(_T("IDF"), _T("DefaultIDFVersion"), version);
	return true;
}

CString	CArchiveProcGUIApp::GetIDFRepository()
{
	CString rc(L""); 

	rc = GetProfileString(_T("IDF"), _T("DefaultIDFRepository"));
	
	return rc;
}
bool	CArchiveProcGUIApp::SetIDFRepository(CString &repository)
{
	WriteProfileString(_T("IDF"), _T("DefaultIDFRepository"), repository);
	return true;
}

const char *CArchiveProcGUIApp::GetImageName(const CString& PathFileName)
{
	const char *rc = '\0';

	int end = PathFileName.GetLength() - 4;			//remove .bmp
	int start = PathFileName.ReverseFind('\\');
	if ((end > start) && (start > 0 ))
	{
		start++;
		rc = MxUtils::WideCharsToAscii_1(PathFileName.Mid(start, end-start));
	}
	return rc;
}


int CArchiveProcGUIApp::UserMsg(const char *Msg, const char *SuggestedAction, UINT Prompt)
{
	int rc = IDOK;

//!!!!!!!!!!!!!!!
#ifdef _DEBUG
	MxUtils::OutputDebugMsg("CArchiveProcGUIApp::UserMsg()", "Msg=%s", (Msg != '\0') ? Msg : "Msg=null");
#endif
//!!!!!!!!!!!!!!!

	std::string msgUser("Msg: ");
	msgUser += (Msg != '\0') ? Msg : "(none)";
	if ( SuggestedAction != '\0')
	{
		msgUser += "\n\nSuggested Action: ";
		msgUser += SuggestedAction;
	}

	rc = AfxMessageBox(CString(msgUser.c_str()), Prompt);

	return rc;
}

void CArchiveProcGUIApp::UserErrorMsg(const char *errorType, const char *ErrorMsg, const char *RecoveryMsg, const char *SuggestedAction, UINT Prompt)
{
//!!!!!!!!!!!!!!!
#ifdef _DEBUG
	MxUtils::OutputDebugMsg("CArchiveProcGUIApp::UserErrorMsg()", "Type=%s, Msg=%s", (errorType != '\0') ? errorType : "Type=null", (ErrorMsg != '\0') ? ErrorMsg : "ErrorMsg=null");
#endif
//!!!!!!!!!!!!!!!

	std::string errMsgUser((errorType != '\0') ? errorType : "(unknown error type)");
	errMsgUser += ": ";
	errMsgUser += (ErrorMsg != '\0') ? ErrorMsg : "(none)";
	errMsgUser += "\n\nRecovery: ";
	errMsgUser += (RecoveryMsg != '\0') ? RecoveryMsg : "successful";
	errMsgUser += "\n\nSuggested Action: ";
	errMsgUser += (SuggestedAction != '\0') ? SuggestedAction : "upon fatal or internal error restart application, otherwise retry operation";

	AfxMessageBox(CString(errMsgUser.c_str()), Prompt );
}

// CArchiveProcGUIApp message handlers

// CAboutDlg dialog used for App About

class CAboutDlg : public CDialogEx
{
public:
	CAboutDlg();

// Dialog Data
	enum { IDD = IDD_ABOUTBOX };

protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV support

// Implementation
protected:
	DECLARE_MESSAGE_MAP()
public:
	CString m_Licence;
};

CAboutDlg::CAboutDlg() : CDialogEx(CAboutDlg::IDD)
	, m_Licence(AppLicenceText)
{

}

void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialogEx::DoDataExchange(pDX);
	DDX_Text(pDX, IDC_EDIT1, m_Licence);
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx)

END_MESSAGE_MAP()

// App command to run the dialog
void CArchiveProcGUIApp::OnAppAbout()
{
	CAboutDlg aboutDlg;
	aboutDlg.DoModal();
}

// CArchiveProcGUIApp customization load/save methods

void CArchiveProcGUIApp::PreLoadState()
{
	BOOL bNameValid;
	CString strName;
	bNameValid = strName.LoadString(IDS_EDIT_MENU);
	ASSERT(bNameValid);
	GetContextMenuManager()->AddMenu(strName, IDR_POPUP_EDIT);
	bNameValid = strName.LoadString(IDS_EXPLORER);
	ASSERT(bNameValid);
	GetContextMenuManager()->AddMenu(strName, IDR_POPUP_EXPLORER);
}

void CArchiveProcGUIApp::LoadCustomState()
{
}

void CArchiveProcGUIApp::SaveCustomState()
{
}

// CArchiveProcGUIApp message handlers




//-------------------------------------------------------------------------------------------------
//			E N D   O F   F I L E
//-------------------------------------------------------------------------------------------------







